package com.jsb.laundry.service.shops.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.jsb.laundry.common.config.Constant;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.ResultPage;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.BCUtil;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.QRCodeUtil;
import com.jsb.laundry.common.utils.aliyun.AliOSSUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.common.utils.push.WxSendServiceImpl;
import com.jsb.laundry.dao.factory.LaundryFactoryDao;
import com.jsb.laundry.dao.shops.LaundryShopsDao;
import com.jsb.laundry.model.factory.JsbOrdersItem;
import com.jsb.laundry.model.factory.*;
import com.jsb.laundry.model.shops.JsbOrdersFulfillmentItem;
import com.jsb.laundry.model.shops.*;
import com.jsb.laundry.service.shops.LaundryShopsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class LaundryShopsServiceImpl implements LaundryShopsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LaundryShopsServiceImpl.class);
    @Resource
    private LaundryShopsDao laundryShopsDao;

    @Resource
    private LaundryFactoryDao laundryFactoryDao;

    /**
     * 订单入店铺表 jsb_orders_shop、jsb_orders_shop_item
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized int orderEnterShops(ShopOrderVo shopOrder) {
        JsbOrders jsbOrders = laundryShopsDao.getOrderInfo(shopOrder);
        shopOrder.setTrackingDirection(jsbOrders.getOrderDirection());
        JsbOrdersShop jsbOrdersShop = laundryShopsDao.getShopsOrderInfo(shopOrder);
        if (jsbOrdersShop == null) {//不存在时，则入库

            /**
             * 入店铺表 jsb_orders_shop
             */
            //获取订单物流信息
            JsbOrdersFulfillment jsbOrdersFulfillment = laundryShopsDao.getOrdersFulfillment(shopOrder);

            JsbOrdersShop orderShop = new JsbOrdersShop();
            orderShop.setOrderId(jsbOrders.getOrderId()).setUserId(jsbOrders.getUserId())
                    .setShopId(jsbOrders.getShopId()).setRiderId(jsbOrdersFulfillment.getTrackingCarrierId())
                    .setShopOrdersStatus("1").setOrderDirection(jsbOrders.getOrderDirection());
            int var0 = laundryShopsDao.addOrdersShop(orderShop);
            /**
             * 入店铺表 jsb_orders_shop_item
             */
            List<JsbOrdersItem> subOrderList = laundryShopsDao.getSubOrderList(orderShop);
            List<JsbOrdersShopItem> orderShopItemList = subOrderList.stream()
                    .map(orderShopItem -> {
                        JsbOrdersShopItem item = new JsbOrdersShopItem();
                        item.setOrderId(orderShopItem.getOrderId())
                                .setSubOrderId(orderShopItem.getSubOrderId())
                                .setTrackingDirection(jsbOrders.getOrderDirection())
                                .setShopId(orderShop.getShopId());

                        return item;
                    }).collect(Collectors.toList());
            /**
             * 填充水洗标
             */
            if ("1".equals(jsbOrders.getOrderDirection())) {
                List<String> subOrderIds = subOrderList.stream()
                        .map(JsbOrdersItem::getSubOrderId).collect(Collectors.toList());
                List<MultipartFile> files = new ArrayList();
                for (String subOrderId : subOrderIds) {
                    BufferedImage bufferedImage = BCUtil.getBarCodeWithWords(subOrderId, subOrderId);
                    MultipartFile multipartFile = BCUtil.convertToMultipartFile(bufferedImage);
                    files.add(multipartFile);
                }
                List<String> imgUrlList = AliOSSUtil.batchUploadImg(files, "shopPrintWashLabel");
                // 填充水洗标
                orderShopItemList = orderShopItemList.stream()
                        .peek(item -> {
                            int index = subOrderIds.indexOf(item.getSubOrderId());
                            if (index >= 0 && index < imgUrlList.size()) {
                                item.setWashLabel(imgUrlList.get(index));
                            }
                        })
                        .collect(Collectors.toList());
            }
            int var1 = laundryShopsDao.addOrdersShopItem(orderShopItemList);
            /**
             * 主订单表jsb_orders订单状态调整
             * station_status 小站/旗舰店状态 0未入库 1已入库 2已出库（对应司机或骑手接单）
             * 表状态默认为0，可不做操作
             */
        }
        return 1;
    }

    /**
     * 第一个方向 订单入店铺表（旗舰店入库的） jsb_orders_shop、jsb_orders_shop_item ( 司机点确认送达 subOrderIds:[] )
     *
     * @param shopOrder
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int orderEnterShopsPlus(ShopOrderVo shopOrder) {
        List<String> subOrderIds = shopOrder.getSubOrderIds();
        /**
         *  子订单
         */
        List<JsbOrdersShopItem> ordersShopItems = laundryShopsDao.getOrderShopItem(subOrderIds);
        //订单方向为 tracking_direction=2 shop_orders_item_status=1
        for (JsbOrdersShopItem ordersShopItem : ordersShopItems) {
            ordersShopItem.setTrackingDirection("1").setShopOrdersItemStatus("1");
            ordersShopItem.setTempId(ordersShopItem.getShopId());
            ordersShopItem.setShopId(ordersShopItem.getNextToId());
            ordersShopItem.setNextToId(ordersShopItem.getTempId());
        }
        int i = laundryShopsDao.addOrdersShopItem(ordersShopItems);
        /**
         * 父订单
         */
        List<JsbOrdersShopItem> distinctItems = ordersShopItems.stream()
                .collect(Collectors.toMap(JsbOrdersShopItem::getOrderId, item -> item, (prev, curr) -> prev))
                .values()
                .stream()
                .collect(Collectors.toList());

        List<JsbOrdersShop> ordersShopListInfo = laundryShopsDao.getShopsOrderInfoList(distinctItems);
        for (JsbOrdersShop jsbOrdersShop : ordersShopListInfo) {
            for (JsbOrdersShopItem distinctItem : distinctItems) {
                if (distinctItem.getOrderId().equals(jsbOrdersShop.getOrderId())) {
                    jsbOrdersShop.setTempId(distinctItem.getShopId());
                    jsbOrdersShop.setNextToId(jsbOrdersShop.getTempId());
                    jsbOrdersShop.setShopId(distinctItem.getNextToId());
                    break;
                }
            }
        }


        for (JsbOrdersShop jsbOrdersShop : ordersShopListInfo) {
            JsbOrders orderInfo = laundryShopsDao.getOrderInfos(jsbOrdersShop);
            if (orderInfo == null) {
                jsbOrdersShop.setOrderDirection("1").setShopOrdersStatus("1").setShopId(jsbOrdersShop.getNextToId()).setNextToId(jsbOrdersShop.getShopId()).setRiderId(null);
                laundryShopsDao.addOrdersShop(jsbOrdersShop);
            }
        }
        return i;
    }

    /**
     * 第二个方向 订单入店铺表 jsb_orders_shop、jsb_orders_shop_item ( 司机点确认送达 subOrderIds:[] )
     *
     * @param shopOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized int orderEnterShopsBack(ShopOrderVo shopOrder) {
        List<String> subOrderIds = shopOrder.getSubOrderIds();
        /**
         *  子订单
         */
        List<JsbOrdersShopItem> ordersShopItems = laundryShopsDao.getOrderShopItem(subOrderIds);
        //订单方向为 tracking_direction=2 shop_orders_item_status=1
        for (JsbOrdersShopItem ordersShopItem : ordersShopItems) {
            ordersShopItem.setTrackingDirection("2").setShopOrdersItemStatus("1");
            ordersShopItem.setNextToId(null);
            ordersShopItem.setShopId(ordersShopItem.getShopId());
        }
        int i = laundryShopsDao.addOrdersShopItem(ordersShopItems);

        /**
         * 父订单
         */
        List<JsbOrdersShopItem> distinctItems = ordersShopItems.stream()
                .collect(Collectors.toMap(JsbOrdersShopItem::getOrderId, item -> item, (prev, curr) -> prev))
                .values()
                .stream()
                .collect(Collectors.toList());
        List<JsbOrdersShop> ordersShopListInfo = laundryShopsDao.getShopsOrderInfoList(distinctItems);

        for (JsbOrdersShop jsbOrdersShop : ordersShopListInfo) {
            JsbOrders orderInfo = laundryShopsDao.getOrderInfos(jsbOrdersShop);
            if (orderInfo == null) {
                jsbOrdersShop.setOrderDirection("2").setShopOrdersStatus("1").setRiderId(null);
                laundryShopsDao.addOrdersShop(jsbOrdersShop);
            }
        }
        return i;
    }

    /**
     * 批量出库入库状态调整 in_check\out_check 更新瑕疵、图片等
     *
     * @param shopOrder
     * @return
     */
    @Transactional
    @Override
    public WebResponse updShopsOrderStatus(ShopOrderVo shopOrder) {
//        List<JsbOrdersShopItem> var0 = laundryShopsDao.checkShopsOrderStatus(shopOrder);
//        if (!JSBUtil.isEmptyCollection(var0)) { //有未检查的出库或入库商品
//            if ("1".equals(shopOrder.getInCheckStatus()) && "1".equals(shopOrder.getTrackingDirection())) {
//                var0 = var0.stream()
//                        .filter(item -> "0".equals(item.getInCheck())).collect(Collectors.toList());
//                return WebResponse.success(ReturnStatusCode.SHOP_IN_CHECK_STATUS.getCode(), ReturnStatusCode.SHOP_IN_CHECK_STATUS.getMsg() + var0.get(0).getOrderId());
//            } else if ("1".equals(shopOrder.getOutCheckStatus()) && "2".equals(shopOrder.getTrackingDirection())) {
//                var0 = var0.stream()
//                        .filter(item -> "0".equals(item.getOutCheck())).collect(Collectors.toList());
//                return WebResponse.success(ReturnStatusCode.SHOP_IN_CHECK_STATUS.getCode(), ReturnStatusCode.SHOP_IN_CHECK_STATUS.getMsg() + var0.get(0).getOrderId());
//            }
//        }
        int var1 = laundryShopsDao.updShopsOrderStatus(shopOrder);

        //出库填充出库二维码
        if (("1".equals(shopOrder.getTrackingDirection()) || "2".equals(shopOrder.getTrackingDirection()))
                && "1".equals(shopOrder.getInCheckStatus())) {
            List<String> subOrderIds = shopOrder.getSubOrderIds();
            List<JsbOrdersFulfillmentItem> items = laundryShopsDao.getOrdersFulfillmentItem(subOrderIds);
            List<String> subOrderIds1 = items.stream().map(JsbOrdersFulfillmentItem::getOrderFulfillmentsId).collect(Collectors.toList());

            List<MultipartFile> files = new ArrayList();
            for (String subOrderId : subOrderIds1) {
                BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(subOrderId);
                MultipartFile multipartFile = QRCodeUtil.convertToMultipartFile(bufferedImage);
                files.add(multipartFile);
            }
            List<String> imgUrlList = AliOSSUtil.batchUploadImg(files, "shopPrintQRCode");
            for (int i = 0; i < subOrderIds.size(); i++) {
                String url = imgUrlList.get(i);
                String subOrderId = subOrderIds.get(i);
                int var2 = laundryShopsDao.updShopQRCode(shopOrder.getTrackingDirection(), subOrderId, url);
            }
        }


        /**
         * TODO 第一个方向出库时，判断衣物是发往工厂还是 旗舰店(普通洗且上级有旗舰店的发往旗舰店)
         */
        orderToWhere(shopOrder);

        /**
         * 添加操作记录
         */
//        int var2 = laundryShopsDao.addOrderStatusLog();

        return WebResponse.successData(var1);
    }

    /**
     * 确认 出库入库
     *
     * @param shopOrder
     * @return
     */
    @Transactional
    @Override
    public WebResponse confirmShopsOrder(ShopOrderVo shopOrder) {
        List<JsbOrdersShopItem> var0 = laundryShopsDao.checkShopsOrderStatus(shopOrder);
        if (!JSBUtil.isEmptyCollection(var0)) { //有未检查的出库或入库商品
            var0 = var0.stream()
                    .filter(item -> "0".equals(item.getInCheck()))
                    .filter(item -> "0".equals(item.getOutCheck()))
                    .collect(Collectors.toList());
            return WebResponse.success(ReturnStatusCode.SHOP_IN_CHECK_STATUS.getCode(), ReturnStatusCode.SHOP_IN_CHECK_STATUS.getMsg() + var0.size());
        }

        /**
         * 更新 jsb_orders_shop_item 中状态
         */
        int var1 = laundryShopsDao.confirmShopsOrder1(shopOrder);

        /**
         * 订单中所有子订单全部入库订单状态才调整为已入库
         */
        List<JsbOrdersShopItem> shopSubOrderList1 = laundryShopsDao.getShopSubOrderList1(shopOrder.getSubOrderIds(), shopOrder.getTrackingDirection());
        List<JsbOrdersShopItem> distinctItems = shopSubOrderList1.stream()
                .collect(Collectors.toMap(JsbOrdersShopItem::getOrderId, item -> item, (prev, curr) -> prev))
                .values()
                .stream()
                .collect(Collectors.toList());


        for (JsbOrdersShopItem distinctItem : distinctItems) {

            ShopOrderVo shopOrderVo = new ShopOrderVo();
            shopOrderVo.setSubOrderIds(Arrays.asList(distinctItem.getSubOrderId()))
                    .setTrackingDirection(distinctItem.getTrackingDirection())
                    .setInCheckStatus(distinctItem.getInCheck())
                    .setOutCheckStatus(distinctItem.getOutCheck())
                    .setOrderId(distinctItem.getOrderId())
                    .setUid(shopOrder.getUid())
            ;
//            List<String> allInShop = laundryShopsDao.checkAllSuborderInOutShop(shopOrder); //子订单已全部入库或出库的 主订单id
            int inShopNum = laundryShopsDao.getAllSuborderInShopNum(shopOrderVo); //当前订单子订单总数量
            int currentNum = laundryShopsDao.getCurrentSuborderOnShopNum(shopOrderVo);  //1方向 出库, 2 方向入库子订单数量
            if (inShopNum == currentNum) {//子订单已全部入库或出库的 主订单id
                shopOrderVo.setAllInOutShopOrderIdList(Arrays.asList(distinctItem.getOrderId()));
                //  更新 jsb_orders_shop 中状态
                int var2 = laundryShopsDao.confirmShopsOrder2(shopOrderVo);
                //  更新 jsb_orders 中状态
//                if ("2".equals(distinctItem.getTrackingDirection())) {
                int var3 = laundryShopsDao.confirmShopsOrder3(shopOrderVo);
//                }

                /**
                 * 第二个方向出库推送信息给骑手、用户
                 */
                pushMsgToUser(shopOrderVo);
                pushMsgToRider(shopOrderVo);
            }


        }
        /**
         *  TODO 第一个方向出库时,添加数据到 jsb_orders_driver_item 中
         */
        orderToDriverItem(shopOrder);

        /**
         * TODO 第一个方向出库时，判断衣物是发往工厂还是 旗舰店(普通洗且上级有旗舰店的发往旗舰店)
         */
//        orderToWhere(shopOrder);

        /**
         *  TODO 入库后 给小站 添加待结算
         */
        addSettlementToShop(shopOrder);


        return WebResponse.successData(1);
    }

    /**
     * 第二个方向出库推送信息给用户
     */
    private void pushMsgToUser(ShopOrderVo shopOrder) {

        if ("2".equals(shopOrder.getTrackingDirection()) && "1".equals(shopOrder.getOutCheckStatus())) {
            JsbOrders orderInfo = laundryShopsDao.getOrderInfo(shopOrder);
            String orderId = orderInfo.getOrderId();
            String userId = orderInfo.getUserId();
            //推送给用户 订阅号
            WxSend.WxUserSend wxUserSend = new WxSend.WxUserSend();
            Map map = laundryFactoryDao.findUserOrderInfo(userId, orderId);
            wxUserSend.setCharacter_string1(orderId);
            wxUserSend.setThing2(map.get("goodsTitle").toString());
            if ("1".equals(map.get("sendType").toString())) { //(1:小哥送达，2:顺丰送达)
                wxUserSend.setThing3("聚洗衣专员配送");
                wxUserSend.setCharacter_string4(map.get("qsBackId").toString()); //我们的payId
            } else {
                wxUserSend.setThing3("顺丰配送");
                wxUserSend.setCharacter_string4(map.get("sfBackId").toString()); //顺丰快递单号
            }
            wxUserSend.setTime5(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            wxUserSend.setOpenId(map.get("openId").toString());
            wxUserSend.setTemplateId("WUxYitOWjqFTQn_CQ_RN_2Ye7x-XOIaWgVghIY9K2w8"); //模板id
            WxSendServiceImpl.send(wxUserSend);
        }

    }

    /**
     * 第二个方向出库推送信息给骑手
     *
     * @param shopOrder
     */
    private void pushMsgToRider(ShopOrderVo shopOrder) {

        if ("2".equals(shopOrder.getTrackingDirection()) && "1".equals(shopOrder.getOutCheckStatus())) {
            JsbOrders orderInfo = laundryShopsDao.getOrderInfo(shopOrder);
            String payId = orderInfo.getOrderId();
            Matcher matcher = Pattern.compile("\\D").matcher(payId);// 匹配非数字字符
            String orderId = matcher.replaceAll("");

            //微信公众号推送骑手
            JSONObject time13 = new JSONObject();
            JSONObject character_string8 = new JSONObject();
            JSONObject object = new JSONObject();
            object.put("character_string8", character_string8);
            object.put("time13", time13);
            character_string8.put("value", orderId);//订单号  int类型
            time13.put("value", JSBUtil.dateFormat(new Date()));//下单时间

            //获取骑手openid,下单成功给所有表骑手用户发送通知
            //下单成功给所有表骑手用户发送通知
            List<WxRiderList> byqOpenId = laundryFactoryDao.findByqOpenId();

            for (WxRiderList wxRiderList : byqOpenId) {
                WxSendServiceImpl.sendLaundry(object, wxRiderList.getOpenId());
            }
        }

    }


    /**
     店铺出库提醒骑手
     Matcher matcher = Pattern.compile("\\D").matcher(distinctItem.getOrderId());// 匹配非数字字符
     String orderId = matcher.replaceAll("");

     //微信公众号推送骑手
     JSONObject time13 = new JSONObject();
     JSONObject character_string8 = new JSONObject();
     JSONObject object = new JSONObject();
     object.put("character_string8", character_string8);
     object.put("time13", time13);
     character_string8.put("value", orderId);//订单号  int类型
     time13.put("value", JSBUtil.dateFormat(new Date()));//下单时间

     //获取骑手openid,下单成功给所有表骑手用户发送通知
     //下单成功给所有表骑手用户发送通知
     List<WxRiderList> byqOpenId = laundryFactoryDao.findByqOpenId();

     for (WxRiderList wxRiderList : byqOpenId) {
     WxSendServiceImpl.sendLaundry(object, wxRiderList.getOpenId());
     }
     *
     */

    /**
     * uid、subOrderIds、trackingDirection
     * 衣物发往 工厂 OR 旗舰店
     * (普通洗且上级有旗舰店的发往旗舰店)
     *
     * @param shopOrder
     */
    public void orderToWhere(ShopOrderVo shopOrder) {
        //TODO 第一个方向出库时，判断衣物是发往工厂还是 旗舰店(普通洗且上级有旗舰店的发往旗舰店)
        if ("1".equals(shopOrder.getTrackingDirection()) && "1".equals(shopOrder.getInCheckStatus())) {
            List<JsbOrdersItem> ordersItems = laundryShopsDao.getSubOrderIdInfoList(shopOrder.getSubOrderIds());
            //上级有旗舰店送的衣物
            List<JsbOrdersItem> normalList = ordersItems.stream()
                    .filter(item -> "普通".equals(item.getWashingType()))
                    .collect(Collectors.toList());

            List<JsbOrdersItem> otherList = ordersItems.stream()
                    .filter(item -> "".equals(item.getWashingType()) || !"普通".equals(item.getWashingType()))
                    .collect(Collectors.toList());

            //查询工厂
            List<Shops> factory = laundryShopsDao.getFactory();
            //获取上级是否有旗舰店
            String shopPlusId = laundryShopsDao.getHaveShopPlus(shopOrder.getUid());
            if (!JSBUtil.isEmptyString(shopPlusId)) { //上级有旗舰店,把普通洗送往旗舰店

                /**
                 * 送往旗舰店的衣物
                 */
                if (!JSBUtil.isEmptyCollection(normalList)) {
                    normalList.stream().forEach(item -> item.setNextToId(shopPlusId));
                    int var0 = laundryShopsDao.updOrderShopItem(normalList);
                }

                /**
                 * 送往工厂的衣物
                 */
                if (!JSBUtil.isEmptyCollection(otherList)) {
                    otherList.stream().forEach(item -> item.setNextToId(factory.get(0).getShopsId() == null ? "formal11" : factory.get(0).getShopsId()));
                    int var1 = laundryShopsDao.updOrderShopItem(otherList);
                }
                LOGGER.info("上级有旗舰店:{},普通洗送往旗舰店:{},其他送往工厂:{}", shopOrder, normalList, otherList);
            } else { //没有全送工厂
                if (!JSBUtil.isEmptyCollection(ordersItems)) {
                    ordersItems.stream().forEach(item -> item.setNextToId(factory.get(0).getShopsId() == null ? "formal11" : factory.get(0).getShopsId()));
                    int var2 = laundryShopsDao.updOrderShopItem(ordersItems);
                }

                LOGGER.info("全部送往工厂:{}", shopOrder);
            }
        }
    }

    /**
     * 入库后 给小站 添加待结算
     *
     * @param shopOrder
     */
    public void addSettlementToShop(ShopOrderVo shopOrder) {

        if (("1".equals(shopOrder.getTrackingDirection()) && "1".equals(shopOrder.getInCheckStatus()))
                || ("2".equals(shopOrder.getTrackingDirection()) && "1".equals(shopOrder.getOutCheckStatus()))) {
            /**
             * 异常件不用再次入
             */
            JsbOrderException orderException = laundryShopsDao.getOrderException(shopOrder);
            if (!JSBUtil.isEmptyObject(orderException)) {
                return;
            }
            List<String> subOrderIdList = new ArrayList(new HashSet(shopOrder.getSubOrderIds()));

            List<JsbOrdersItem> orderList = laundryShopsDao.getProductAndOrderInfo(subOrderIdList, shopOrder.getTrackingDirection());
            for (JsbOrdersItem jsbOrdersItem : orderList) {
                //当前单小站分佣
                int currentAmount = (int) (jsbOrdersItem.getPaidPrice() * jsbOrdersItem.getProportion() * Constant.rider_commission_percentage);

                Map<String, Object> map = new HashMap();
                map.put("shopsId", shopOrder.getUid());
                if ("1".equals(shopOrder.getTrackingDirection())) {
                    map.put("orderId", jsbOrdersItem.getOrderFulfillmentsId());
                } else if ("2".equals(shopOrder.getTrackingDirection())) {
                    map.put("orderId", jsbOrdersItem.getOrderFulfillmentsId() + "A");
                }
                map.put("amount", currentAmount);

                /**
                 * 防止同一笔分佣多次存入 (存在则跳过)
                 */
                String remarkOrderId = "小站分佣:"+map.get("orderId");
                int checkShopCommission = laundryShopsDao.checkShopCommission(remarkOrderId);
                if (checkShopCommission != 0) {
                    continue;
                }

                String res = HttpUtil.sendPost("http://127.0.0.1:20000/riderOrder/system/siteCommission", null, JSONObject.toJSONString(map));
                LOGGER.info("入库后 给小站 添加待结算。入参：{},出参：{}", map, res);
            }

        }
    }

    /**
     * 出库时，第一个方向出库时,添加数据到 jsb_orders_driver_item 中,不是异常件才往司机表中插入
     *
     * @param shopOrder
     */
    public void orderToDriverItem(ShopOrderVo shopOrder) {


        if ("1".equals(shopOrder.getTrackingDirection()) && "1".equals(shopOrder.getOutCheckStatus())) {
            /**
             * 异常件不用再次入司机表
             */
            JsbOrderException orderException = laundryShopsDao.getOrderException(shopOrder);
            if (!JSBUtil.isEmptyObject(orderException)) {
                return;
            }


            List<JsbOrdersItem> ordersItemList = laundryShopsDao.getShopSubOrderList(shopOrder);
            List<JsbOrdersFulfillmentItem> list = laundryShopsDao.getOrdersDriverItem(shopOrder.getSubOrderIds(), shopOrder.getTrackingDirection());
            for (JsbOrdersItem jsbOrdersItem : ordersItemList) {
                for (JsbOrdersFulfillmentItem jsbOrdersFulfillmentItem : list) {
                    if (jsbOrdersFulfillmentItem.getOrderItemId().equals(jsbOrdersItem.getSubOrderId())) {
                        jsbOrdersItem.setCome(jsbOrdersItem.getShopId())
                                .setBack(jsbOrdersItem.getNextToId())
                                .setOrderDirection("1")
                                .setOrderFulfillmentsId(jsbOrdersFulfillmentItem.getOrderFulfillmentsId())
                                .setTrackingNumber(jsbOrdersFulfillmentItem.getTrackingNumber());
                        break;
                    }
                }
            }
//            for (JsbOrdersItem jsbOrdersItem : ordersItemList) {
//                jsbOrdersItem.setCome(jsbOrdersItem.getShopId())
//                        .setBack(jsbOrdersItem.getNextToId())
//                        .setOrderDirection("1")
//                        .setOrderFulfillmentsId(JSBUtil.generateLongOrderId())
//                        .setTrackingNumber(JSBUtil.generateLongOrderId());
//            }

            int var0 = laundryShopsDao.addOrderToDriverItem(ordersItemList);
            LOGGER.info("商铺已出库订单入司机表jsb_orders_driver_item中:{}", ordersItemList);
        }
    }

    /**
     * 小站管理详情
     *
     * @param shopOrder
     * @return
     */
    @Override
    public ShopsManagerDetailVo getShopsManagerDetail(ShopOrderVo shopOrder) {
        ShopsManagerDetailVo detailVo = new ShopsManagerDetailVo();
        //开启分页
        PageHelper.startPage(shopOrder.getPageNum(), shopOrder.getPageSize());
        //小站已结算和待结算订单
        List<ShopOrderVo> shopsOrderList = laundryShopsDao.getShopsOrderList(shopOrder);
        if (JSBUtil.isEmptyCollection(shopsOrderList)) {
            shopsOrderList = new ArrayList() {
                {
                    add(new ShopOrderVo());
                }
            };
        }

        //小站详情
        ShopsManagerDetailVo.ShopInfo shopInfo = laundryShopsDao.getShopsManagerDetail(shopOrder);
        detailVo.setShopInfo(shopInfo).setOrderInfoList(shopsOrderList);
        return detailVo;
    }

    /**
     * 骑手管理详情
     *
     * @param shopOrder
     * @return
     */
    @Override
    public RiderManagerDetailVo getRiderManagerDetail(ShopOrderVo shopOrder) {
        RiderManagerDetailVo detailVo = new RiderManagerDetailVo();
        //开启分页
        PageHelper.startPage(shopOrder.getPageNum(), shopOrder.getPageSize());
        //小站已结算和待结算订单
        List<ShopOrderVo> shopsOrderList = laundryShopsDao.getShopsOrderList(shopOrder);
        if (JSBUtil.isEmptyCollection(shopsOrderList)) {
            shopsOrderList = new ArrayList() {
                {
                    add(new ShopOrderVo());
                }
            };
        }

        //小站详情
        RiderManagerDetailVo.RiderInfo riderInfo = laundryShopsDao.getRiderManagerDetail(shopOrder);
        detailVo.setRiderInfo(riderInfo).setOrderInfoList(shopsOrderList);

        return detailVo;
    }

    /**
     * 客户管理详情
     *
     * @param shopOrder
     * @return
     */
    @Override
    public UserManagerDetailVo getUserManagerDetail(ShopOrderVo shopOrder) {
        UserManagerDetailVo detailVo = new UserManagerDetailVo();
        //开启分页
        PageHelper.startPage(shopOrder.getPageNum(), shopOrder.getPageSize());
        //小站已结算和待结算订单
        List<ShopOrderVo> shopsOrderList = laundryShopsDao.getShopsOrderList(shopOrder);
        if (JSBUtil.isEmptyCollection(shopsOrderList)) {
            shopsOrderList = new ArrayList() {
                {
                    add(new ShopOrderVo());
                }
            };
        }

        //小站详情
        UserManagerDetailVo.UserInfo userInfo = laundryShopsDao.getUserManagerDetail(shopOrder);
        detailVo.setUserInfo(userInfo).setOrderInfoList(shopsOrderList);

        return detailVo;
    }

    /**
     * 经营概览-旗舰店
     *
     * @param shopOrder
     * @return
     */
    @Override
    public ShopHomeVo getShopHome(ShopHomeVo shopOrder) {
        ShopHomeVo shopHomeVo = new ShopHomeVo();
        /**
         * TODO 店铺信息
         */
        ShopHomeVo.ShopInfo shopInfo = laundryShopsDao.getShopHome1(shopOrder);
        Integer yesterdayOrderNum = shopInfo.getYesterdayOrderNum() == 0 ? 1 : shopInfo.getYesterdayOrderNum();
        Integer currentDayOrderNum = shopInfo.getCurrentDayOrderNum();
        //(今日-昨日)/昨日
        int orderNumRate = ((currentDayOrderNum - yesterdayOrderNum) / yesterdayOrderNum) * 100;
        shopInfo.setOrderNumRate(String.valueOf(orderNumRate));

        /**
         * TODO 代办事项
         */
        ShopHomeVo.AgentMatters agentMatters = laundryShopsDao.getShopHome2(shopOrder);

        shopHomeVo.setShopInfo(shopInfo).setAgentMatters(agentMatters);
        return shopHomeVo;
    }

    @Override
    public ShopHomeVo getShopHomeManageData(ShopHomeVo shopOrder) {
        ShopHomeVo shopHomeVo = new ShopHomeVo();
        /**
         * TODO 经营数据
         */
        ShopHomeVo.ManageData manageData = laundryShopsDao.getShopHome3(shopOrder);

        shopHomeVo.setManageData(manageData);
        return shopHomeVo;
    }

    @Override
    public ShopHomeVo getShopHomeIncreaseTrend(ShopHomeVo shopOrder) {
        ShopHomeVo shopHomeVo = new ShopHomeVo();

        /**
         * TODO 增长趋势
         */
        List<ShopHomeVo.IncreaseTrend> increaseTrend = laundryShopsDao.getShopHome4(shopOrder);
        if (JSBUtil.isEmptyCollection(increaseTrend)) {
            increaseTrend = new ArrayList() {
                {
                    add(new ShopHomeVo.IncreaseTrend());
                }
            };
        }
        shopHomeVo.setIncreaseTrend(increaseTrend);
        return shopHomeVo;
    }

    @Override
    public FundManageHomeVo fundManageHome(ShopsBankCard shopsBankCard) {
        /**
         * 资金管理首页头部
         */
        FundManageHomeVo fundManageHomeVo = laundryShopsDao.fundManageHome1(shopsBankCard);

        //开启分页
        PageHelper.startPage(fundManageHomeVo.getPageNum(), fundManageHomeVo.getPageSize());
        /**
         * 提现记录list
         */
        List<Withdrawals> withdrawalsList = laundryShopsDao.fundManageHome2(shopsBankCard);
        if (JSBUtil.isEmptyCollection(withdrawalsList)) {
            withdrawalsList = new ArrayList() {
                {
                    add(new Withdrawals());
                }
            };
        }

        ResultPage< List<Withdrawals>> returnData = new ResultPage<>(withdrawalsList);
        fundManageHomeVo.setPageSize(returnData.getPageSize())
                .setPageNum(returnData.getPageNum())
                .setTotal(returnData.getTotal())
                .setWithdrawalsList(withdrawalsList);

        return fundManageHomeVo;
    }

    /**
     * 账单管理
     *
     * @param shopsBankCard
     * @return
     */
    @Override
    public Object fundManageDetail(FundManageDetailVo shopsBankCard) {
        FundManageDetailVo vo = laundryShopsDao.fundManageDetail1(shopsBankCard);

        //开启分页
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<FundManageDetailVo.SettleInfo> settleInfoList = laundryShopsDao.fundManageDetail2(shopsBankCard);
//        if (JSBUtil.isEmptyCollection(settleInfoList)) {
//            settleInfoList = new ArrayList() {
//                {
//                    add(new FundManageDetailVo.SettleInfo());
//                }
//            };
//        }
        ResultPage<List<FundManageDetailVo.SettleInfo>> returnData = new ResultPage<>(settleInfoList);
        vo.setPageSize(returnData.getPageSize())
                .setPageNum(returnData.getPageNum())
                .setTotal(returnData.getTotal())
                .setSettleInfoList(settleInfoList);
        return vo;
    }


}
